package com.ruben.simplescaffold.pojo.common;

import org.springframework.http.HttpStatus;

import java.util.HashMap;
import java.util.Optional;

/**
 * 自定义返回响应
 *
 * @author <achao1441470436@gmail.com>
 * @since 2021/6/23 10:40
 */
public class Result extends HashMap<String, Object> {
    public static final String DATA_KEY = "data";
    private static final long serialVersionUID = 8639693790921600208L;
    /**
     * 成功状态
     */
    private static final String SUCCESS_KEY = "success";
    /**
     * 消息
     */
    private final String MSG_KEY = "msg";
    /**
     * 状态码
     */
    private final String CODE_KEY = "code";

    public static Result ok() {
        return httpStatus(HttpStatus.OK);
    }

    public static Result error(String msg) {
        return httpStatus(HttpStatus.INTERNAL_SERVER_ERROR).msg(msg);
    }

    public static Result paramError() {
        return httpStatus(HttpStatus.BAD_REQUEST);
    }

    public static Result notLogin() {
        return httpStatus(HttpStatus.UNAUTHORIZED);
    }

    public static Result httpStatus(HttpStatus httpStatus) {
        httpStatus = Optional.ofNullable(httpStatus).orElse(HttpStatus.OK);
        HttpStatus.Series series = httpStatus.series();
        return new Result().success(httpStatus.is2xxSuccessful()).msg(series.name()).code(httpStatus.value());
    }

    public Result success(Boolean success) {
        this.put(SUCCESS_KEY, success);
        return this;
    }

    public String msg() {
        return (String) this.get(MSG_KEY);
    }

    public Result msg(String msg) {
        this.put(MSG_KEY, msg);
        return this;
    }

    public Integer code() {
        return (Integer) this.get(CODE_KEY);
    }

    public Result code(Integer code) {
        this.put(CODE_KEY, code);
        return this;
    }

    public Boolean isSuccess() {
        return (Boolean) this.get(SUCCESS_KEY);
    }

    /**
     * 放入key和value
     *
     * @param key   键
     * @param value 值
     * @return Result
     * @author <achao1441470436@gmail.com>
     * @since 2021/6/23 17:07
     */
    @Override
    public Result put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    /**
     * 返回数据
     *
     * @param value 数据
     * @return Result
     * @author <achao1441470436@gmail.com>
     * @since 2021/6/23 17:07
     */
    public Result data(Object value) {
        this.put(DATA_KEY, value);
        return this;
    }

}